package com.banciyuan.bcywebview.biz.detail.noveldetail.newnoveldetail;

import android.animation.ObjectAnimator;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.TimelineLikeHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.dialog.ChargeSuccDialog;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.recycleview.FixLinearLayoutManager;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.detail.adapter.DetailConstants;
import com.banciyuan.bcywebview.biz.detail.charge.ChargeRankActivity;
import com.banciyuan.bcywebview.biz.detail.charge.ChargeSelectActivity;
import com.banciyuan.bcywebview.biz.detail.charge.PayHelper;
import com.banciyuan.bcywebview.biz.detail.charge.PayHelperInter;
import com.banciyuan.bcywebview.biz.detail.comment.CommentConstants;
import com.banciyuan.bcywebview.biz.detail.comment.CommentHelper;
import com.banciyuan.bcywebview.biz.detail.complex.helper.ComplexHelper;
import com.banciyuan.bcywebview.biz.detail.complex.helper.ComplexHelperInter;
import com.banciyuan.bcywebview.biz.detail.complex.holder.FloatBottom;
import com.banciyuan.bcywebview.biz.detail.complex.holder.FloatTop;
import com.banciyuan.bcywebview.biz.detail.noveldetail.BookNovelHelper;
import com.banciyuan.bcywebview.biz.detail.noveldetail.NovelIndexActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.baidussp.SimpleImplOnAdlistener;
import com.banciyuan.bcywebview.utils.baidussp.SspHelper;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import de.greenrobot.daoexample.model.ChargeItem;
import de.greenrobot.daoexample.model.Complex;
import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PostCore;
import de.greenrobot.daoexample.model.Role;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Timeline;
import de.greenrobot.daoexample.model.UserDetail;


/**
 * Created by squall on 2017/2/28.
 */

public class NovelComplexActivity extends BaseActivity implements BaseWatcher {

    public static final int GOSHARE = 2000;
    public static final int GOPERSON = 110;
    public static final int GOCHARGE = 113;

    private Gson gson;
    private List<DetailComment> dlist = new ArrayList<>();

    protected View rl_top;
    protected View rl_bottom;
    private View comment_cover;
    protected RecyclerView recyclerView;
    private FixLinearLayoutManager ll_manger;
    private TextView comment_guide;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    protected DetailType mDetailType;
    private NovelComplexAdapter complexAdapter;
    protected int page = 1;
    private boolean is_load = false;
    protected boolean is_end = false;
    private boolean book_flag = false;
    private Complex complex;

    private boolean isRlBottomShowing = true;
    private boolean isBottomAnimRunning = false;
    private boolean isTopAnimRunning = false;
    private boolean isRlTopShowing = false;

    private FloatBottom floatBottom;
    private FloatTop floatTop;
    protected ComplexHelper complexHelper;

    private String from;
    private boolean pushSource;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        readTheme();
        setContentView(R.layout.complex_activity);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initData();
        initAction();
        viewAd();
    }

    private void readTheme() {
        boolean is_light = SPHelper.getBoolean(this, SPConstant.SPNAME_CLOSELIGHT, SPConstant.NOVEL_LIGHT, true);
        if (is_light) {
            setTheme(R.style.AppTheme);
        } else {
            setTheme(R.style.AppThemeDark);
        }
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initArgs() {
        from = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        pushSource = getIntent().getBooleanExtra("pushSource", false);
        gson = new Gson();
        intiDetailType();
        complexHelper = new ComplexHelper(getContext(), mDetailType);
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(NovelComplexActivity.class, this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(NovelComplexActivity.class);
    }

    private void intiDetailType() {
        mDetailType = new DetailType();
        Intent intent = getIntent();
        DetailDataHelper.getBaseDetailVaule(mDetailType, intent);
    }

    @Override
    protected void initUi() {
        recyclerView = (RecyclerView) findViewById(R.id.main_rv);
        rl_top = findViewById(R.id.rl_title_top);
        rl_bottom = findViewById(R.id.rl_bottom);
        floatBottom = new FloatBottom(rl_bottom, this);
        floatTop = new FloatTop(rl_top);
        comment_cover = findViewById(R.id.comment_cover);
        comment_guide = (TextView) findViewById(R.id.comment_guide);
        ll_manger = new FixLinearLayoutManager(this);
        ll_manger.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setHasFixedSize(true);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
    }

    private void judgeFirstShowCommentPic() {
        if (!SPHelper.getBoolean(this, SPConstant.FIRST_SHOW_COMMENT_PIC, false)) {
            comment_cover.setVisibility(View.VISIBLE);
            comment_cover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    comment_cover.setVisibility(View.GONE);
                    SPHelper.putBoolean(NovelComplexActivity.this, SPConstant.FIRST_SHOW_COMMENT_PIC, true);
                }
            });
        }
    }

    @Override
    protected void initAction() {
        recyclerView.addOnScrollListener(new OnResultScrollListener() {

            @Override
            public void onBottom() {
                if (!is_end && complex != null && complex.getStatus() == 1) {
                    page++;
                    getComment();
                }
            }

            @Override
            public void onTop() {
                if (isRlTopShowing && !isTopAnimRunning) {
                    hideTop();
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            hideTop();
                        }
                    }, 200);
                }
            }

            @Override
            public void onBottom(final int FirstVisibleItemPosition) {
                if (is_end) {
                    showBottom();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (!isRlBottomShowing && !isBottomAnimRunning) {
                                showBottom();
                            }
                            if (FirstVisibleItemPosition > 0 && !isRlTopShowing && !isTopAnimRunning) {
                                showTop();
                            }
                        }
                    }, 100);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (lm.findFirstVisibleItemPosition() == 0) {
                    if (isRlTopShowing && !isTopAnimRunning) {
                        hideTop();
                    }
                    return;
                }
                if (dy < -5 && !isRlTopShowing && !isTopAnimRunning) {
                    showTop();
                } else if (dy > 5 && isRlTopShowing && !isTopAnimRunning) {
                    hideTop();
                }
                if (dy > 5 && isRlBottomShowing && !isBottomAnimRunning) {
                    hideBottom();
                } else if (dy < -5 && !isRlBottomShowing && !isBottomAnimRunning) {
                    showBottom();
                }
            }
        });
    }

    @Override
    protected void initData() {
        complexHelper.getDetailData(new ComplexHelperInter() {
            @Override
            public void succ(int status, String result) {
                try {
                    complex = gson.fromJson(result, Complex.class);
                    complex.setStatus(status);
                    complex.setTimelineType(mDetailType.getTimelineType());
                    crateRelaCircle();
                    createRecommendCircle();
                    renderDetailUi();
                    saveBookMark();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(int status) {
                switch (status) {
                    case MyConstants.NOTEXIT:
                    case MyConstants.DATA_NOTEXIT:
                        mProgressbarHelper.onFailed(getString(R.string.content_not_exist));
                        break;
                    case MyConstants.NEED_LOGIN:
                        complex = new Complex();
                        complex.setStatus(MyConstants.NEED_LOGIN);
                        renderDetailUi();
                        break;
                    case MyConstants.SOMETINGS_WRONG:
                        mProgressbarHelper.onFailed();
                        break;
                    case MyConstants.PERSON_NOT_EXIST:
                        mProgressbarHelper.onFailed();
                        break;
                    case MyConstants.WORK_LOKED:
                        complex = new Complex();
                        complex.setStatus(MyConstants.WORK_LOKED);
                        renderDetailUi();
                        break;
                }
            }
        });
    }

    private void createRecommendCircle() {
        List<TagDetail> recommendCircle = new ArrayList<>();
        addWorkToTag(recommendCircle);
        if (null != complex.getPost_tags()) {
            for (int i = 0; i < complex.getPost_tags().size(); i++) {
                TagDetail tagDetail = complex.getPost_tags().get(i);
                if (isLegalRecommendCircle(tagDetail)) {
                    recommendCircle.add(tagDetail);
                }
            }
        }
        complex.setcRecommendCircle(recommendCircle);
    }

    private void addWorkToTag(List<TagDetail> recommendCircle) {
        TagDetail workTagDetail = new TagDetail();
        if (!TextUtils.isEmpty(complex.getWid())) {
            workTagDetail.setType("work");
            workTagDetail.setName(complex.getPost_core().getName());
            workTagDetail.setTag_name(complex.getPost_core().getName());
            workTagDetail.setWork(complex.getPost_core().getName());
            workTagDetail.setIntro(complex.getPost_core().getIntro());
            workTagDetail.setWid(complex.getWid());
            workTagDetail.setCover(complex.getPost_core().getCover());
            workTagDetail.setPost_count(complex.getPost_core().getPost_count());
            recommendCircle.add(workTagDetail);
        }
    }

    private boolean isLegalRecommendCircle(TagDetail tagDetail) {
        try {
            return "event".equals(tagDetail.getType()) || !TextUtils.isEmpty(tagDetail.getPost_count()) && Integer.valueOf(tagDetail.getPost_count()) > 10;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void crateRelaCircle() {
        List<TagDetail> relaCircle = new ArrayList<>();
        addWorkToTag(relaCircle);
        if (null != complex.getPost_tags()) {
            relaCircle.addAll(complex.getPost_tags());
        }
        complex.setRela_circle(relaCircle);
    }

    private void getChargeList() {
        ChargeItem chargeItem = new ChargeItem();
        if (mDetailType.getTimelineType() != TimelineFactory.TIMELINE_TYPE_DAILY) {
            chargeItem.setPost_id(complex.getRp_id());
        } else {
            chargeItem.setPost_id(complex.getUd_id());
        }
        chargeItem.setPost_type(TimelineFactory.getTimeLineTypeName(mDetailType.getTimelineType()));
        PayHelper payHelper = new PayHelper(this);
        payHelper.getPayList(new PayHelperInter() {
            @Override
            public void Succ(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                    Gson gson = new Gson();
                    List<UserDetail> ulist = gson.fromJson(result, new TypeToken<List<UserDetail>>() {
                    }.getType());
                    complex.getPayment().setTop_users(ulist);
                    if (complexAdapter != null) {
                        complexAdapter.notifyItemChanged(complexAdapter.getChargeIndex());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail() {

            }
        }, chargeItem, 1);
    }


    protected void getComment() {
        if (is_load) return;
        is_load = true;
        complexHelper.getCommentData(page, new ComplexHelperInter() {
            @Override
            public void succ(int status, String result) {
                try {
                    List<DetailComment> templist = gson.fromJson(result, new TypeToken<List<DetailComment>>() {
                    }.getType());
                    if (templist.size() > 0) {
                        is_end = templist.get(templist.size() - 1).is_end();
                    } else {
                        is_end = true;
                    }
                    CommentHelper.processTemList(templist);
                    if (page == 1) {
                        dlist.clear();
                    }
                    dlist.addAll(templist);
                    if (complexAdapter != null) {
                        complexAdapter.notifyDataSetChanged();
                    }
                    processCommentSource();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    is_load = false;
                    mProgressbarHelper.onSuccess();
                }
            }

            @Override
            public void fail(int status) {
                is_load = false;
            }
        });
    }

    private void processCommentSource() {
        if (pushSource)
            gotoComment();
        if ((!TextUtils.isEmpty(from) && from.equals("fromComment"))) {
            if (complex.getReply_count() == 0) {
                showComment();
            } else {
                gotoComment();
            }
        }
    }

    private void renderDetailUi() {
        complexAdapter = new NovelComplexAdapter(this, complex, mDetailType, dlist);
        recyclerView.setLayoutManager(ll_manger);
        recyclerView.setAdapter(complexAdapter);
        if (complex.getPayment() != null) {
            if (!TextUtils.isEmpty(complex.getPayment().getStatus())
                    && !TextUtils.isEmpty(complex.getPayment().getUser_count())
                    && !complex.getPayment().getStatus().equals("0")
                    && Integer.parseInt(complex.getPayment().getUser_count()) > 0) {
                getChargeList();
            }
        }
        if (complex.getStatus() != MyConstants.NEED_FANS
                && complex.getStatus() != MyConstants.WORK_LOKED
                && complex.getStatus() != MyConstants.NEED_LOGIN
                && complex.getLock() == null) {
            rl_bottom.setVisibility(View.VISIBLE);
            rl_top.setVisibility(View.VISIBLE);
            floatBottom.processBottom(complex);
            floatTop.processTopHeadData(complex, this);
            randomCommentGuide();
            getComment();
            judgeFirstShowCommentPic();
        } else {
            rl_bottom.setVisibility(View.GONE);
            rl_top.setVisibility(View.GONE);
            mProgressbarHelper.onSuccess();
            from = "";
        }
    }

    private void randomCommentGuide() {
        String[] array = null;
        if (complex.getReply_count() == 0) {
            array = getResources().getStringArray(R.array.reply_0_content);
        } else {
            array = getResources().getStringArray(R.array.reply_not_0_content);
        }
        Random random = new Random();
        String text = array[random.nextInt(array.length - 1)];
        if (!TextUtils.isEmpty(text)) {
            comment_guide.setText(text);
        }
    }

    protected void showTop() {
        if (null == rl_top)
            return;
        ObjectAnimator.ofFloat(rl_top, "translationY", UIUtils.dip2px(60, this))
                .setDuration(200).start();
        isTopAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlTopShowing = true;
                isTopAnimRunning = false;
            }
        }, 200);
    }

    protected void hideTop() {
        if (null == rl_top)
            return;
        ObjectAnimator.ofFloat(rl_top, "translationY", 0)
                .setDuration(200).start();
        isTopAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlTopShowing = false;
                isTopAnimRunning = false;
            }
        }, 200);
    }


    protected void showBottom() {
        if (null == rl_bottom)
            return;
        ObjectAnimator.ofFloat(rl_bottom, "translationY", 0)
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = true;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    protected void hideBottom() {
        if (null == rl_bottom)
            return;
        ObjectAnimator.ofFloat(rl_bottom, "translationY", UIUtils.dip2px(133, this))
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = false;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    protected void showShare() {
        boolean showDelBtn = UserDataHelper.ifLogin(this) && StringUtil.notNullEqual(complex.getProfile().getUid(), UserDataHelper.getInstance(this).getUid());
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showDelBtn", showDelBtn);
        intent.putExtra("timeline", parseComplexToTimeline(complex));
        startActivityForResult(intent, GOSHARE);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void showCharge() {
        Intent intent = new Intent(this, ChargeSelectActivity.class);
        intent.putExtra("content", complex.getPayment().getIntro());
        if (complex.getTimelineType() != TimelineFactory.TIMELINE_TYPE_DAILY) {
            intent.putExtra("post_id", complex.getRp_id());
        } else {
            intent.putExtra("post_id", complex.getUd_id());
        }
        intent.putExtra("uid", complex.getProfile().getUid());
        intent.putExtra("type", TimelineFactory.getTimeLineTypeName(complex.getTimelineType()));
        startActivityForResult(intent, GOCHARGE);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void showComment() {
        Intent intent = new Intent(this, EditActivity.class);
        intent.putExtra(CommentConstants.SHOW_CHARGE, false);
        intent.putExtra(CommentConstants.COMMENT_HINT, comment_guide.getText().toString().trim());
        DetailDataHelper.putBaseDetailValue(intent, mDetailType);
        startActivityForResult(intent, CommentConstants.GO_COMMENT);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void showRecommend() {
        TimelineLikeHelper.doRecommendAll(this, VolleyQueue.getRquest(this), mDetailType, String.valueOf(complex.isHave_tuijian()), new TimelineLikeHelper.TimelineSuccess() {
            @Override
            public void onTimelineSuccess() {
                complex.setHave_tuijian(!complex.isHave_tuijian());
                floatBottom.updateTuijian(complex);
            }
        });
    }

    private void showDing() {
        complexHelper.doLike(complex, new TimelineLikeHelper.TimelineSuccess() {
            @Override
            public void onTimelineSuccess() {
                if (complex.isHave_ding()) {
                    complex.setDing_num(complex.getDing_num() - 1);
                    complex.setHave_ding(false);
                } else {
                    complex.setDing_num(complex.getDing_num() + 1);
                    complex.setHave_ding(true);
                }
                floatBottom.updateDing(complex);
            }
        });
    }

    private void getChargeUser(UserDetail user) {
        List<UserDetail> ulist = complex.getPayment().getTop_users();
        if (ulist.size() >= 3) {
            ulist.get(2).setUid(user.getUid());
            ulist.get(2).setAvatar(user.getAvatar());
        } else {
            ulist.add(user);
        }
        int count = Integer.parseInt(complex.getPayment().getUser_count()) + 1;
        complex.getPayment().setUser_count(String.valueOf(count));
        if (complexAdapter != null) {
            complexAdapter.notifyDataSetChanged();
        }
    }

    private Timeline parseComplexToTimeline(Complex complex) {
        Timeline shareTimeline = new Timeline();
        if (!TextUtils.isEmpty(complex.getCover())) {
            shareTimeline.setContentAddress(complex.getCover());
        }
        shareTimeline.setTitle(complex.getTitle());
        shareTimeline.setOUName(complex.getProfile().getUname());
        shareTimeline.setTimelineType(mDetailType.getTimelineType());
        shareTimeline.setRp_id(mDetailType.getRp_id());
        shareTimeline.setWp_id(mDetailType.getWp_id());
        shareTimeline.setCp_id(mDetailType.getCp_id());
        shareTimeline.setDp_id(mDetailType.getDp_id());
        shareTimeline.setUd_id(mDetailType.getUd_id());
        shareTimeline.setPost_id(mDetailType.getPost_id());
        shareTimeline.setGid(mDetailType.getGid());
        shareTimeline.setUid(complex.getProfile().getUid());
        shareTimeline.setTags(complex.getPost_tags());
        shareTimeline.setWork(complex.getWork());
        shareTimeline.setType(complex.getType());
        ArrayList<String> roleNames = new ArrayList<>();
        if (complex.getProperties().getCharacter() != null) {
            for (Role role : complex.getProperties().getCharacter()) {
                roleNames.add(role.getRole_name());
            }
            shareTimeline.setOriginalRoleNames(roleNames);
        }
        return shareTimeline;
    }


    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.FOLLOW_EVENT:
                if (complex != null && complex.getProfile() != null) {
                    complex.getProfile().setFollowstate("havefollow");
                }
                floatTop.focus_tv.setVisibility(View.GONE);
                if (complexAdapter != null) {
                    complexAdapter.notifyItemChanged(0);
                }
                break;
            case BaseObserver.FOLLOW_EVENT_REFREASH:
                initData();
                break;
            case BaseObserver.DELETE_EVENT:
                finish();
                break;
            case BaseObserver.FINISH_EVENT:
                finish();
                break;
            case BaseObserver.CHARGE_EVENT:
                showCharge();
                break;
            case BaseObserver.RECOMMEND_EVENT:
                showRecommend();
                break;
            case BaseObserver.COMMENT_EVENT:
                int type = (int) object;
                if (1 == type && complex.getReply_count() != 0) {
                    gotoComment();
                } else {
                    showComment();
                }
                break;
            case BaseObserver.SHARE_EVENT:
                showShare();
                break;
            case BaseObserver.LIKE_EVENT:
                showDing();
                break;
            case BaseObserver.DELELE_COMMENT_EVENT:
                deleteComment((Integer) object);
                break;
            case BaseObserver.LIKE_COMMENT_EVENT:
                LikeComment((Integer) object);
                break;
            case BaseObserver.DISLIKE_COMMENT_EVENT:
                disLikeComment((Integer) object);
                break;
            case BaseObserver.GO_PERSON:
                Intent intent = new Intent(this, SmoothPersonActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, complex.getProfile().getUid());
                startActivityForResult(intent, GOPERSON);
                break;
            case BaseObserver.DELETE:
                final View view = findViewById(R.id.delete_lock);
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        view.setVisibility(View.VISIBLE);
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                alertDel();
                            }
                        });
                    }
                });
                break;
            case BaseObserver.NOVEL_GO_INDEX:
                if (!TextUtils.isEmpty(complex.getSet_data().getWns_id())) {
                    gotoUtil.gotoAct(this, NovelIndexActivity.class, complex.getSet_data().getWns_id());
                }
                break;
            case BaseObserver.NOVEL_DONOT_BOOK:
                dobook(false);
                break;
            case BaseObserver.NOVEL_DO_BOOK:
                dobook(true);
                break;
            case BaseObserver.NOVEL_GO_NEXT:
                doNextCharpter();
                break;
            case BaseObserver.NOVEL_GO_PRE:
                doPreCharpter();
                break;
            case BaseObserver.CHARGE_RANK:
                gotoChargeRank();
                break;
            case BaseObserver.LIGHT:
                switchLight((Boolean) object);
                break;
        }
    }

    private void gotoChargeRank() {
        ChargeItem chargeItem = new ChargeItem();
        if (complex.getTimelineType() != TimelineFactory.TIMELINE_TYPE_DAILY) {
            chargeItem.setPost_id(complex.getRp_id());
        } else {
            chargeItem.setPost_id(complex.getUd_id());
        }
        chargeItem.setPost_type(TimelineFactory.getTimeLineTypeName(complex.getTimelineType()));
        gotoUtil.gotoAct(this, ChargeRankActivity.class, chargeItem);
    }

    private void switchLight(boolean flag) {
        if (flag) {
            SPHelper.putBoolean(this, SPConstant.SPNAME_CLOSELIGHT, SPConstant.NOVEL_LIGHT, false);
        } else {
            SPHelper.putBoolean(this, SPConstant.SPNAME_CLOSELIGHT, SPConstant.NOVEL_LIGHT, true);
        }
        if (mDetailType != null) {
            Intent intent = new Intent(this, NovelComplexActivity.class);
            intent.putExtra(MyConstants.RPIDVALUE, mDetailType.getRp_id());
            intent.putExtra(MyConstants.WPIDVALUE, mDetailType.getWp_id());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(MyConstants.TIMELINETYPE, TimelineFactory.TIMELINE_TYPE_WRITER);
            startActivity(intent);
            overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
        }
    }

    private void doNextCharpter() {
        if (!TextUtils.isEmpty(complex.getSet_data().getSet_post_next()) && !complex.getSet_data().getSet_post_next().equals("0")) {
            mProgressbarHelper.onLoading();
            page = 1;
            is_end = false;
            is_load = false;
            mDetailType.setRp_id(complex.getSet_data().getSet_post_next());
            initData();
        }
    }

    public void doPreCharpter() {
        if (!TextUtils.isEmpty(complex.getSet_data().getSet_post_prev()) && !complex.getSet_data().getSet_post_prev().equals("0")) {
            mProgressbarHelper.onLoading();
            page = 1;
            is_end = false;
            is_load = false;
            mDetailType.setRp_id(complex.getSet_data().getSet_post_prev());
            initData();
        }
    }

    private void dobook(final boolean isbook) {
        if (book_flag) return;
        book_flag = true;
        BookNovelHelper.doBook(this, isbook, complex.getSet_data().getWns_id(), new BookNovelHelper.NovelBookSuccess() {
            @Override
            public void onBookSuccess() {
                if (isbook) {
                    MyToast.show(NovelComplexActivity.this, getString(R.string.book_succ));
                } else {
                    MyToast.show(NovelComplexActivity.this, getString(R.string.debook_succ));
                }
                complex.getSet_data().setSubscribed(isbook);
                complexAdapter.notifyItemChanged(1);
                book_flag = false;
            }

            @Override
            public void onBookError() {
                book_flag = false;
            }
        });
    }

    private void alertDel() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.confrim_to_delete))
                .setActionString(getString(R.string.mydialog_delete))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delPost();
                    }
                })
                .create().show();
    }

    public void delPost() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, NovelComplexActivity.this)) {
                    BaseObserver.getInstance().notifyWatchers(BaseObserver.DELETE_EVENT);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        CommonApiUtils.delPost(this, VolleyQueue.getRquest(this), onSuccess, onError, complex);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GOPERSON) {
            mProgressbarHelper.onLoading();
            initData();
        } else if (requestCode == GOSHARE) {
            if (resultCode == ShareActivity.DELETE) {
                finish();
            } else if (resultCode == DetailConstants.EDIT_TAGS) {
                List<TagDetail> tags = (List<TagDetail>) data.getSerializableExtra("tags");
                complex.setPost_tags(tags);
                PostCore postCore = (PostCore) data.getSerializableExtra("postcore");
                if (null != postCore) {
                    complex.setWork(postCore.getName());
                    complex.setWid(postCore.getId());
                    complex.setPost_core(postCore);
                }
                crateRelaCircle();
                createRecommendCircle();
                complexAdapter.notifyDataSetChanged();
            }
        } else if (requestCode == GOCHARGE) {
            if (resultCode == ChargeSelectActivity.PAY_SUCC) {
                if (!isFinishing() && data != null) {
                    getChargeUser((UserDetail) data.getSerializableExtra("userdetail"));
                    boolean showNormalDialog = data.getBooleanExtra("under_700", true);
                    ChargeSuccDialog chargeSuccDialog = new ChargeSuccDialog(this, R.style.Dialog);
                    chargeSuccDialog.showNormalPic(showNormalDialog);
                    chargeSuccDialog.setDetailType(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getContext(), EditActivity.class);
                            intent.putExtra(CommentConstants.CONTENT, getContext().getString(R.string.dafult_pay_comment));
                            intent.putExtra(CommentConstants.SHOW_CHARGE, true);
                            intent.putExtra(CommentConstants.COMMENT_TYPE, 3);
                            DetailDataHelper.putBaseDetailValue(intent, mDetailType);
                            startActivityForResult(intent, CommentConstants.GO_COMMENT);
                            overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                        }
                    });
                    chargeSuccDialog.show();
                }
            }
        } else if (requestCode == CommentConstants.GO_REPLY && resultCode == EditActivity.END_ADD) {
            complex.setReply_count(complex.getReply_count() + 1);
            floatBottom.updateComment(complex);
            dealAddReply(data);
        } else if (requestCode == CommentConstants.GO_COMMENT && resultCode == EditActivity.END_ADD) {
            complex.setReply_count(complex.getReply_count() + 1);
            floatBottom.updateComment(complex);
            dealAddComment(data);
            recyclerView.scrollToPosition(complexAdapter.getCommentStartIndex());
        }
    }

    private void dealAddComment(Intent data) {
        DetailComment detailComment = (DetailComment) data.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        if (null != complexAdapter) {
            dlist.add(0, detailComment);
            complexAdapter.notifyItemInserted(complexAdapter.getCommentStartIndex() + 1);
            complexAdapter.notifyItemRangeChanged(complexAdapter.getCommentStartIndex(), complexAdapter.getCommentSize() + 2);
        }
    }

    private void dealAddReply(Intent data) {
        DetailComment replyDetail = (DetailComment) data.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        int pos = data.getIntExtra(gotoUtil.INTENT_VALUE_TWO, -1);
        if (null != complexAdapter) {
            if (pos != -1) {
                DetailComment commentDetail = dlist.get(pos);
                int commentCount = commentDetail.getComments_count() + 1;
                commentDetail.setComments_count(commentCount);
                List<DetailComment> comments = commentDetail.getComments();
                if (null == comments) {
                    comments = new ArrayList<>();
                    commentDetail.setComments(comments);
                }
                comments.add(0, replyDetail);
            }
            complexAdapter.notifyItemChanged(complexAdapter.getCommentIndex() + pos);
            complexAdapter.notifyItemChanged(complexAdapter.getCommentStartIndex());
        }
    }

    private void gotoComment() {
        if (complexAdapter != null) {
            from = "";
            pushSource = false;
            ll_manger.scrollToPositionWithOffset(complexAdapter.getCommentStartIndex(), 0);
        }
    }

    private void deleteComment(int position) {
        if (dlist != null && !dlist.isEmpty() && position < dlist.size()) {
            DetailComment deleteComment = dlist.remove(position);
            int deleteNum = 1 + deleteComment.getComments_count();
            complex.setReply_count(complex.getReply_count() - deleteNum);
            floatBottom.updateComment(complex);
            if (complexAdapter != null) {
                complexAdapter.notifyItemRemoved(complexAdapter.getCommentIndex() + position);
                complexAdapter.notifyItemRangeChanged(complexAdapter.getCommentStartIndex(), complexAdapter.getCommentSize() + 2);
            }
        }
    }

    private void disLikeComment(int position) {
        if (dlist != null && !dlist.isEmpty() && position < dlist.size()) {
            DetailComment detailComment = dlist.get(position);
            detailComment.setHave_ding(false);
            detailComment.setDing_num(detailComment.getDing_num() - 1);
            if (complexAdapter != null) {
                complexAdapter.notifyItemChanged(complexAdapter.getCommentIndex() + position);
            }
        }
    }

    private void LikeComment(int position) {
        if (dlist != null && !dlist.isEmpty() && position < dlist.size()) {
            DetailComment detailComment = dlist.get(position);
            detailComment.setHave_ding(true);
            detailComment.setDing_num(detailComment.getDing_num() + 1);
            if (complexAdapter != null) {
                complexAdapter.notifyItemChanged(complexAdapter.getCommentIndex() + position);
            }
        }
    }

    private void viewAd() {
        SspHelper sspHelper = new SspHelper(this);
        if (mDetailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_WRITER) {
            sspHelper.getViewCount(MyConstants.ADS_ID_NOVEL, new SimpleImplOnAdlistener());
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        try {
            menu.add(0, v.getId(), 0, getString(R.string.copy_paste));
            TextView textView = (TextView) v;
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("shareText", textView.getText().toString());
            clipboard.setPrimaryClip(clipData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveBookMark() {
        if (complex != null && null != complex.getSet_data()) {
            String save = complex.getRp_id() + "#" + complex.getSet_data().getPost_pos();
            SPHelper.putString(this, SPConstant.SPNAME_BOOKMARK, complex.getSet_data().getWns_id(), save);
        }
    }

}
